<?php

class ProductController extends \AdminController {
    protected $layout = 'admin::layouts.master';
    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $dataPost = array(
            'keySearch' => '',
            'manufacturer_id' => '',
            'category_id' => ''
        );

        if (Request::isMethod('post')) {
            $dataPost['keySearch'] = Input::get('keySearch');
            $dataPost['manufacturer_id'] = Input::get('manufacturer_id');
            $dataPost['category_id'] = Input::get('category_id');
        }

        $products = Product::getList($dataPost, Config::get('constants.PAGING_NUMBER'));

        $manufacturer  = Manufacturer::getList();
        $category      = Category::getList();

        $data = array('products' => $products,
            'category'      => $category,
            'manufacturer'  => $manufacturer,
            'data' => $dataPost
        );

        return View::make('admin::product.index', $data)->with('title', 'List Product');
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        $product       = new Product();
        $manufacturer  = Manufacturer::getList();
        $category      = Category::getList();

        $data = array('product' => $product,
            'category' => $category,
            'manufacturer' => $manufacturer,
        );

        return View::make('admin::product.create', $data)->with('title', 'Create product');
    }


    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        if (Request::isMethod('post')) {
            $product = Product::find(Input::get('id'));

            $rules = array(
                'product_name'      => 'required|min:5|max:50',
                'product_quantity'  => 'required|Integer|min:1|max:999',
                'product_price'     => 'required|Integer|min:1|max:9999999999',
                'category_id'       => 'required|Integer|min:1|max:99',
                'manufacturer_id'   => 'required|Integer|min:1|max:99'
            );

            $validator = Validator::make(Input::all(), $rules);

            if ($validator->fails()) {
                return Redirect::to($this->packageAdmin.'/admin/product/create')->withErrors($validator)->withInput()->with('title', 'Create product');
            } else {
                if (!$product){
                    $product = new Product();
                }

                $product->product_name      = Input::get('product_name');
                $product->product_model     = Input::get('product_model');
                $product->category_id       = Input::get('category_id');
                $product->manufacturer_id   = Input::get('manufacturer_id');
                $product->created_id        = Auth::user()->id;
                $product->product_price     = Input::get('product_price');
                $product->product_quantity    = Input::get('product_quantity');
                $product->product_description = Input::get('product_description');
                $product->product_keywords = Input::get('product_keywords');
                $product->product_url_seo = Input::get('product_url_seo');
                $product->product_image_main  = Input::get('product_image_main');
                $product->product_image_thumbnail = Input::get('product_image_thumbnail');
                $product->product_content = Input::get('product_content');
                $product->status  = Input::get('status');

                $flagSave = false;
                DB::beginTransaction();
                session_start();

                if ($product->id) {
                    if ($product->update()) {
                        $flagSave = true;
                    } else {
                        DB::rollback();
                    }
                } else {
                    if ($product->save()) {
                        $flagSave = true;
                    } else {
                        DB::rollback();
                    }
                }

                if ($flagSave) {
                    $product->product_image_main = str_replace(session_id(), $product->id, $product->product_image_main);
                    $product->product_image_main = str_replace('tmp-folder', Config::get('constants.UPLOAD.PRODUCT_FOLDER_NAME'), $product->product_image_main);
                    $product->product_image_thumbnail = str_replace(session_id(), $product->id, $product->product_image_thumbnail);
                    $product->product_image_thumbnail = str_replace('tmp-folder', Config::get('constants.UPLOAD.PRODUCT_FOLDER_NAME'), $product->product_image_thumbnail);

                    $dataPost = array(
                        'image_main_path' => $_POST['product_image_main'],
                        'image_thumbnail_path' => $_POST['product_image_thumbnail'],
                        'product_folder_name'  => Config::get('constants.UPLOAD.PRODUCT_FOLDER_NAME')
                    );

                    Utility::copyImage($product, $dataPost);
                    DB::commit();

                    return Redirect::to($this->packageAdmin.'/admin/product')->with('success', 'Product saved in successful.');
                }
            }
        }

        $product       = new Product();
        $manufacturer  = Manufacturer::getList();
        $category      = Category::getList();

        $data = array('product' => $product,
            'category' => $category,
            'manufacturer' => $manufacturer,
        );

        return View::make('admin::product.create', $data)->with('title', 'Create product');
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function show($id)
    {
        if ($id) {
            $product = Product::find($id);

            if ($product) {
                return View::make('admin::product.view', array('product' => $product))->with('title', $product->product_name);
            } else {
                return Redirect::to('dtu/admin/product')->with('flash_error', 'Product id ='. $id. ' not found.');
            }
        }

        return Redirect::to('dtu/admin/product');
    }


    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        if ($id) {
            $product = DB::table('Product')->find($id);

            if ($product) {
                $manufacturer  = Manufacturer::getList();
                $category      = Category::getList();

                $data = array('product' => $product,
                    'category'     => $category,
                    'manufacturer' => $manufacturer,
                );

                return View::make('admin::product.create', $data)->with('title', $product->product_name);
            } else {

                return Redirect::to('dtu/admin/product')->with('flash_error', 'Product id '. $id. ' not found.');
            }
        }

        return Redirect::to('/dtu/admin/product');
    }


    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy($id)
    {
        $product = User::find($id);

        if ($product) {
            if ($product->delete_flag == 1) {
                $product->delete_flag = 0;
            } else {
                $product->delete_flag = 1;
            }

            if ($product->update(array('delete_flag'))) {
                return Redirect::route('product')->with('flash_error', 'Product id '. $id. ' deleted.');
            }
        }

        return Redirect::route('product')->with('flash_error', 'Product id '. $id. ' not found.');
    }

    public function updateStatus()
    {
        $data = array(
            'error'  => true,
            'status' => 0
        );

        if (Request::isMethod('get') && $id = Request::get('id')) {

            $product = Product::find($id);

            if ($product) {
                if ($product->status == 0) {
                    $product->status = 1;
                    $data['status'] = 1;
                } else {
                    $product->status = 0;
                    $data['status'] = 0;
                }

                if ($product->update(array('status'))) {
                    $data['error'] = false;
                }
            }
        }


        return Response::json($data);
    }
}
